const model = require('./server/model')
const baseUrl = `https://www.manhuatai.com`
var Nightmare = require('nightmare');
let cheerio = require('cheerio')
let nightmare = Nightmare({
  show: true, width: 1920, height: 1080,
  waitTimeout: 10000,
  // openDevTools: {
  //   mode: 'bottom'
  // }
});

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

class Main {
  constructor(mainPageUrl) {
    this.mainPageUrl = mainPageUrl
    this.chapterInfos = []
  }
  async getMainPage() {
    await nightmare.goto(this.mainPageUrl).inject('js', 'jquery.min.js').wait('#topic1');
    let topic = await nightmare.evaluate((mainPageUrl) => {
      let $lis = $('.jshtml li')
      return {
        code: 'dpcq',
        name: $lis.eq(0).text().replace('名称：', ''),
        author: $lis.eq(2).text().replace('作者：', ''),
        url: mainPageUrl,
        avatar: $('.comic-cover img').attr('src'),
        update_at: $lis.last().text().replace('更新：', ''),
      }
    }, this.mainPageUrl)
    if (await model.ComicTopic.getBy({ code: topic.code }) == null)
      await model.ComicTopic.create(topic)

    await nightmare.click('.mhrtitle .bgyellow').wait('#topic1>li')
    this.chapterInfos = await nightmare.evaluate(() => {
      return document.querySelector('.mhlistbody').innerHTML
    }).then(html => {
      const $ = cheerio.load(html)
      let chapterInfos = []
      let $chapters = $('#topic1>li a')
      console.log('len', $chapters.length)
      $chapters.each((i, dom) => {
        let href = $(dom).attr('href')
        chapterInfos.push({
          cid: href.substring(href.lastIndexOf('/') + 1, href.lastIndexOf('.')),
          title: $(dom).text(),
          url: baseUrl + href,
          num: i + 1,
          topic: 'dpcq'
        })
      })
      return chapterInfos
    })

    await model.ComicChapter.deleteBy({ topic: topic.code })
    await model.ComicChapter.bulkCreate(this.chapterInfos)
    for (let x of this.chapterInfos) {
      if (x.num == 2){
        this.getChapter(x)
      }
    }
  }
  async getChapter(chapter) {
    console.log('chapter',chapter)
    let x=chapter
    await nightmare.goto(x.url).inject('js', 'jquery.min.js').wait('.mh_comicpic img')
    let total = 0;
    let contents = []
    let content = await this.getContent(x.cid)
    contents.push(content)

    total = content.total
    for (let j = 1; j < total; j++) {
      await nightmare.click('.mh_comicpic img').inject('js', 'jquery.min.js').wait('.mh_comicpic img')
      contents.push(await this.getContent(x.cid))
    }
    console.log(contents)
    await model.ComicContent.deleteBy({ cid: x.cid, topic: x.topic })
    await model.ComicContent.bulkCreate(contents)
    return contents
  }

  async getContent(cid) {
    let content = await nightmare.evaluate((cid) => {
      let $img = $('.mh_comicpic img').eq(0)
      let $select = $('.mh_select').eq(0)
      return {
        cid,
        img_url: $img.attr('src'),
        width: $img.width(),
        height: $img.height(),
        num: $select.val(),
        total: $select.find('option').length,
        topic: 'dpcq'
      }
    }, cid)
    return content
  }
}
// https://www.manhuatai.com/doupocangqiong/
let main = new Main(`${baseUrl}/doupocangqiong`);

// main.getMainPage();

module.exports = main;